﻿// Author:					HungNM
// Created:					16-08-2012
// Last Modified:			16-08-2012
//

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using eProject.Business;
using System.Text;
using System.Globalization;


namespace eProject.Web.UI
{
    public partial class AddRoutePage : System.Web.UI.Page
    {
        private long routeId = -1;
        private long scheduleId = -1;
        private Routes route;
        private Schedules schedule;

        protected void Page_Load(object sender, EventArgs e)
        {
            LoadParams();
            LoadSettings();
            PopulateLabels();
            PopulateControls();
        }

        private void PopulateControls()
        {

        }

        private void BindDropDownList()
        {
            List<AirPorts> lstAirPort = AirPorts.GetAll();
            Cities city;
            ddlFrom.Items.Clear();
            foreach (AirPorts air in lstAirPort)
            {
                city = new Cities(air.CityId);
                ddlFrom.Items.Add(new ListItem(city.Name + " (" + air.AirPortId + ")", air.Id.ToString()));
                ddlTo.Items.Add(new ListItem(city.Name + " (" + air.AirPortId + ")", air.Id.ToString()));
            }

            List<Planes> plane = Planes.GetAll();
            ddlPlaneId.DataSource = plane;
            ddlPlaneId.DataTextField = "planeId";
            ddlPlaneId.DataValueField = "Id";
            ddlPlaneId.DataBind();
        }

        protected void btnInsertSchedule_Click(object sender, EventArgs e)
        {
            if (routeId > 0)
            {
                route = new Routes(this.routeId);
                schedule = new Schedules(this.routeId);

                StringBuilder script = new StringBuilder();

                string scheduleType = rdlScheduleType.SelectedValue;
                if ("Week".Equals(scheduleType))
                {
                    int n = chkListSchedule.Items.Count;
                    if (n > 0)
                    {
                        for (int i = 0; i < n; i++)
                        {
                            if (chkListSchedule.Items[i].Selected)
                            {
                                if (script.Length > 0)
                                    script.Append(",");
                                script.Append(chkListSchedule.Items[i].Value);
                            }
                        }
                    }
                }
                else
                    script.Append(scheduleType);
                

                schedule.RouteId = route.Id;
                schedule.EffectDate = DateTime.ParseExact(txtEffectDate.Text.Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
                schedule.Available = chkAvailable.Checked;
                schedule.DepartureTime = txtDepartureTime.Text.Trim();
                schedule.ArrivalTime = txtArrivalTime.Text.Trim();
                schedule.ScheduleType = script.ToString();
                if (schedule.Save())
                    Response.Redirect(Request.RawUrl);
                    
                
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.routeId > 0)
                {
                    route = new Routes(this.routeId);
                }
                else
                { route = new Routes(); }
                long planeId = Convert.ToInt64(ddlPlaneId.SelectedValue.ToString());
                long cityFrom = Convert.ToInt64(ddlFrom.SelectedValue.ToString());
                long cityTo = Convert.ToInt64(ddlTo.SelectedValue.ToString());
                long distance = Convert.ToInt64(txtDistance.Text.ToString());

                
                route.From = cityFrom;
                route.To = cityTo;
                route.PlaneId = planeId;
                route.Distance = distance;
                if (route.Save())
                    Response.Redirect("AddRoute.aspx?Id=" + route.Id);
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }

        protected void btnInsertPrice_Click(object sender, EventArgs e)
        {
            try
            {
                int seatClassId = Convert.ToInt32(ddlSeatClass.SelectedValue);
                decimal ticketPrice = Convert.ToDecimal(txtSeatPrice.Text);

                if (routeId > 0)
                {
                    schedule = new Schedules(this.routeId);
                    if (schedule.Id > 0)
                    {
                        ScheduleTicketPrice ticket = new ScheduleTicketPrice();
                        ticket.ScheduleId = schedule.Id;
                        ticket.SeatClassId = seatClassId;
                        ticket.Price = ticketPrice;
                        if (ticket.Save())
                        {
                            BindTicket();
                            Response.Redirect(Request.RawUrl);
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }

        public string GetSeatName(object seatId)
        {
            int seatClassId = Convert.ToInt32(seatId);
            SeatClass seat = new SeatClass(seatClassId);
            return seat.SeatName;
        }

        private void PopulateLabels()
        {
            if (IsPostBack) return;
            Title = "Add New Route Page - eProject";
        }

        private void LoadSettings()
        {
            if (IsPostBack) return;
            BindDropDownList();
            if (this.routeId > 0)
            {
                liRouteSchedule.Visible = (this.routeId > 0);
                divRouteSchedule.Visible = (this.routeId > 0);
                route = new Routes(this.routeId);
                ddlPlaneId.ClearSelection();
                ListItem lstItem = ddlPlaneId.Items.FindByValue(route.PlaneId.ToString());
                lstItem.Selected = true;
                ddlFrom.ClearSelection();
                lstItem = ddlFrom.Items.FindByValue(route.From.ToString());
                lstItem.Selected = true;
                ddlTo.ClearSelection();
                lstItem = ddlTo.Items.FindByValue(route.To.ToString());
                lstItem.Selected = true;
                txtDistance.Text = route.Distance.ToString();
                schedule = new Schedules(route.Id);
                scheduleId = schedule.Id;
                if (scheduleId > 0)
                {
                    liRouteSeat.Visible = (scheduleId > 0);
                    divRouteSeat.Visible = (this.routeId > 0);
                    ddlSeatClass.DataSource = SeatClass.GetAllBySchedule(scheduleId);
                    ddlSeatClass.DataTextField = "SeatName";
                    ddlSeatClass.DataValueField = "Id";
                    ddlSeatClass.DataBind();
                    BindTicket();
                    txtEffectDate.Text = schedule.EffectDate.ToString("dd/MM/yyyy");
                    chkAvailable.Checked = schedule.Available;
                    txtDepartureTime.Text = schedule.DepartureTime;
                    txtArrivalTime.Text = schedule.ArrivalTime;
                    ListItem listItem = new ListItem();
                    switch (schedule.ScheduleType)
	                {
                        case "One":
                            listItem = rdlScheduleType.Items.FindByValue("One");
                            listItem.Selected = true;
                            break;
                        case "EveryDay":
                            listItem = rdlScheduleType.Items.FindByValue("EveryDay");
                            listItem.Selected = true;
                            break;
		                default:
                            listItem = rdlScheduleType.Items.FindByValue("Week");
                            listItem.Selected = true;
                            lstSchedule.Style["display"] = "block";
                            string[] arr = schedule.ScheduleType.Split(',');
                            if (arr.Length > 0)
                            {
                                for (int i = 0; i < arr.Length; i++)
                                {
                                    ListItem item = chkListSchedule.Items.FindByValue(arr[i]);
                                    item.Selected = true;
                                }
                            }
                            break;
	                }
                }
            }
        }


        protected void grvTicketPrice_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                long Id = Convert.ToInt64(grvTicketPrice.DataKeys[e.RowIndex].Value.ToString());
                if(ScheduleTicketPrice.Delete(Id))
                    BindTicket();
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }

        private void BindTicket()
        {
            if (routeId > 0)
            {
                schedule = new Schedules(this.routeId);
                if (schedule.Id > 0)
                {
                    grvTicketPrice.DataSource = ScheduleTicketPrice.GetAll(schedule.Id);
                    grvTicketPrice.DataBind();
                }
            }
        }

        private void LoadParams()
        {
            if (Page.Request.QueryString.Count > 0)
            {
                string Id = Page.Request.QueryString["Id"].ToString();
                if (!string.IsNullOrEmpty(Id))
                {
                    this.routeId = Convert.ToInt64(Id);
                }
            }
        }

        #region OnInit

        override protected void OnInit(EventArgs e)
        {
            base.OnInit(e);
            this.Load += new EventHandler(this.Page_Load);
            this.btnSubmit.Click += new EventHandler(btnSubmit_Click);
            this.btnInsertSchedule.Click += new EventHandler(btnInsertSchedule_Click);
            this.btnInsertPrice.Click += new EventHandler(btnInsertPrice_Click);
            this.grvTicketPrice.RowDeleting += new GridViewDeleteEventHandler(grvTicketPrice_RowDeleting);
        }

        #endregion
    }
}